const Koa = require("koa");
const app = new Koa();

const views = require("koa-views");
const onerror = require("koa-onerror");
const json = require("koa-json");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const session = require("koa-generic-session");

// koa连接redis模块
const redisStore = require("koa-redis");

// 日志模块
const morgan = require("koa-morgan");

const path = require("path");
const fs = require("fs");

// 路由模块
const index = require("./routes/index");
const channel = require("./routes/channel");
const goods = require("./routes/goods");
const user = require("./routes/user");
const demo = require("./routes/demo");

// 导入redis配置
const { REDIS_CONF } = require("./conf/db");

// error handler
onerror(app);

// middlewares
app.use(
    bodyparser({
        enableTypes: ["json", "form", "text"],
    })
);

// json支持
app.use(json());

// 日志中间件
app.use(logger());

// 静态资源中间件
app.use(require("koa-static")(path.join(__dirname, "../public")));

// 模板渲染中间件
app.use(
    views(__dirname + "/views", {
        extension: "pug",
    })
);

// 计时中间件
app.use(async (ctx, next) => {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

/* 支持全部 */
const AllowAll = require("./middleware/allowAll")
app.use(AllowAll)

// 拿到运行时环境变量
const ENV = process.env.NODE_ENV;

// 开发环境 / 测试环境
if (ENV !== "production") {
    app.use(morgan("dev"));
}

// 线上环境
else {
    const logFileName = path.join(__dirname, "../logs", "access.log");
    const writeStream = fs.createWriteStream(logFileName, {
        // 追加内容
        flags: "a",
    });
    app.use(
        morgan("combined", {
            stream: writeStream,
        })
    );
}

// session 配置
// 给客户端发cookie作为访问session的信物 该cookie需要加密
app.keys = ["nimei"];
app.use(
    session({
        // 配置 cookie
        cookie: {
            path: "/",
            httpOnly: true,
            maxAge: 24 * 60 * 60 * 1000,
        },

        // 配置 redis
        store: redisStore({
            // all: '127.0.0.1:6379'   // 写死本地的 redis
            all: `${REDIS_CONF.host}:${REDIS_CONF.port}`,
        }),
    })
);

// routes
app.use(index.routes(), index.allowedMethods());
app.use(channel.routes(), channel.allowedMethods());
app.use(goods.routes(), goods.allowedMethods());
app.use(user.routes(), user.allowedMethods());
app.use(demo.routes(), demo.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
    console.error("server error", err, ctx);
});

module.exports = app;
